package zouran.filepractice.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.util.URLEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;

/**
 * 下载文件
 * Author：zouran
 * Date：2023/4/29  20:27
 */
@RestController
@RequestMapping("/download")
public class DownloadFile {
    /**
     *文件路径下载文件
     * eg:
     * fileUrl:D:\study\1.png
     */
    @RequestMapping("/file")
    public String downloadFile( @RequestParam("fileUrl") String fileUrl, HttpServletResponse httpServletResponse) throws IOException {
        File file=new File(fileUrl);
        if(!file.exists())
            return "not exists!";
        //设置返回文件格式,例如image/png
        httpServletResponse.setContentType(Files.probeContentType(Path.of(fileUrl)));
//        attachment 表示以附件方式下载。如果要在页面中打开，则改为 inline
        httpServletResponse.setHeader("content-disposition","attachment;filename="+ URLEncoder.DEFAULT.encode(file.getName(), StandardCharsets.UTF_8));
        //文件路径不存在
        if(!file.exists()) return "error";
        //创建输入流
        try (InputStream inputStream = new FileInputStream(file)) {
            //获取输出流
            OutputStream outputStream = httpServletResponse.getOutputStream();
            //将输入流转为字节流
            byte[] bytes = new byte[1024];
            int length;
            //输出文件流
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
        }
        return "success";
    }
    /**
     *base64图片
     */
    @RequestMapping("/base64Img")
    public String tt() throws IOException {
      String fileUrl="D:\\study\\1.png";
      File file=new File(fileUrl);
      if(!file.exists()){
          return "not exist!";
      }
        byte[] bytes;
        try (InputStream inputStream = new FileInputStream(file)) {
            bytes = inputStream.readAllBytes();
        }
        return "data:image/png;base64,"+Base64.getEncoder().encodeToString(bytes);
    }
}
